import pymysql.constants.FIELD_TYPE

from .mysql_reader import MySqlPlugin


class GbasePlugin(MySqlPlugin):
    conn_type = 'gbase'
    default_conn_name = "conn_id"

    def __init__(self, *args, **kwargs) -> None:
        if "port" not in kwargs:
            kwargs["port"] = 5258
        super(GbasePlugin, self).__init__(*args, **kwargs)

    def get_records(self, sql, parameters=None, cursor=None):
        """
        Executes the sql and returns a set of records.

        :param sql: the sql statement to be executed (str) or a list of
            sql statements to execute
        :param parameters: The parameters to render the SQL query with.
        """
        raw_records = super(GbasePlugin, self).get_records(sql, parameters, cursor)
        cols_desc = self.get_cols_desc(sql)
        cols_convert = {}
        for i, desc in enumerate(cols_desc):
            if desc[1] == pymysql.constants.FIELD_TYPE.NEWDECIMAL and desc[5] > 0:
                cols_convert[i] = float
            elif desc[1] == pymysql.constants.FIELD_TYPE.NEWDECIMAL and desc[5] == 0:
                cols_convert[i] = int

        def default_cov(v):
            return v

        target_records = []
        for record in raw_records:
            # target_records.append(tuple([cols_convert.get(i, default_cov)(d) for i, d in enumerate(record)]))
            target_records.append(tuple(
                [cols_convert.get(i, default_cov)(d) if d is not None and d != "" else d for i, d in
                 enumerate(record)]))
        return target_records

    def get_records_md5_list(self, sql, parameters=None, cursor=None):
        cols = self.get_cols(sql)
        cols_str = "||".join(["IFNULL(%s ,'')" % col for col in cols])
        db_sql = "select upper( MD5( concat( %s ))) as md5 from (%s)" % (cols_str, sql)
        records = super(GbasePlugin, self).get_records(db_sql, parameters, cursor)
        return records

    def get_records_md5(self, sql, parameters=None, cursor=None):
        cols = self.get_cols(sql)
        cols_str = "||".join(["IFNULL(%s ,'')" % col for col in cols])
        db_sql = "select upper( MD5( concat( %s ))) as md5 from (%s)" % (cols_str, sql)
        records = super(GbasePlugin, self).get_records(db_sql, parameters, cursor)
        return records



